﻿using Web.API.IBLL;
using Web.API.IDAL;
using Web.API.Model;

namespace Web.API.BLL
{
    public class UserBLL:UserIBLL
    {
        public UserBLL(UserIDAL<UserModel> dal, UserIDAL<UserTypeModel> dAl) 
        {
            Dal = dal;
            DAl = dAl;
        }
        public UserIDAL<UserModel> Dal { get; }
        public UserIDAL<UserTypeModel> DAl { get;}

        public Task<int> AddUser(UserModel user)
        {
           return Dal.AddAsync(user);
        }

        public Task<int> DelUser(string ids)
        {
            int[] arr = ids.Split(',').Select(x => int.Parse(x)).ToArray();
            List<UserModel> list = Dal.GetAll().Where(x => arr.Contains(x.Id)).ToList();
            foreach (UserModel m in list)
            {
                m.IsDelete = false;
            }
            return Dal.UpdateRangeAsync(list);
        }

        public UserModel Fantian(int id)
        {
            return Dal.GetAll().FirstOrDefault(x=>x.Id==id);
        }

        public dynamic GetUser(string? name, int usertypeid, int index, int size)
        {
            var list = from a in Dal.GetAll().Where(x => x.IsDelete == true)
                       join b in DAl.GetAll() on a.UserTypeId equals b.UserTypeId
                       select new
                       {
                           a.Id,
                           a.Name,
                           a.UserTypeId,
                           a.Img,
                           a.Sex,
                           a.Phone,
                           a.Room,
                           a.Floor,
                           a.Start,
                           UserType= b.Name
                       };
            if (!string.IsNullOrEmpty(name))
            {
                list = list.Where(x=>x.Name.Contains(name));
            }
            if (usertypeid > 0)
            {
                list = list.Where(x=>x.UserTypeId==usertypeid);
            }
            var c = list.Count();
            var d=list.OrderBy(x=>x.Id).Skip((index-1)*size).Take(size).ToList();
            return new
            {
                count=c,
                data=d
            };
        }

        public Task<int> UptStart(string idstring)
        {
            List<int> idlist = idstring.Split(",").Select(x => Convert.ToInt32(x)).ToList();
            var mlist = Dal.GetAll().Where(d => idlist.Contains(d.Id));
            foreach (var m in mlist)
            {
                if (m.Start == true)
                {
                    m.Start = false;
                }
            }
            return Dal.UpdateRangeAsync(mlist.ToList());
        }

        public Task<int> UptUser(UserModel user)
        {
           return Dal.UpdateAsync(user);
        }

        public List<UserTypeModel> Xiala()
        {
            return DAl.GetAll().ToList();
        }

    }
}
